<template>
  <div class="transport-cost w-[100%]">
    <div class="text-[14px] leading-[17px] flex items-center">
      <span class="mr-[4px]">{{ costLabel }}</span>
      <div class="w-[150px]">
        <CurrencySelect v-model="currency" :disabled="type=='add'" @change="handleCurrency"/>
      </div>
    </div>
    <div>
      <div
        class="text-[13px] text-[#333] leading-[20px] mb-[4px] mt-[8px] bg-[var(--base-small-bg-color)] rounded-[8px] px-[8px] py-[8px] overflow-hidden"
      >
        <template v-if="billingType === 1">
          <div
            class="flex items-center whitespace-nowrap"
            :class="{ 'mt-[16px]': index !== 0 }"
            v-for="(item, index) in cost"
            :key="`${item.key}`"
          >
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">
                {{ index == 0 ? "首重" : `续重${index}` }}：不超过
              </span>
              <el-input
                placeholder="请输入"
                v-model="item.max_value"
                @blur="handleWeight(item.max_value, index)"
              >
                <template #append>g</template>
              </el-input>
            </div>
            <div class="mr-[4px] flex items-center">
              <span class="mr-[4px]">计费重量</span>
              <el-input placeholder="请输入" v-model="item.bill_weight">
                <template #append>g</template>
              </el-input>
            </div>
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">单价</span>
              <el-input placeholder="请输入" v-model="item.unit_price">
              </el-input>
            </div>
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">首重折扣</span>
              <el-input placeholder="请输入" v-model="item.discount">
              </el-input>
            </div>
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">首重附加费</span>
              <el-input placeholder="请输入" v-model="item.surcharge">
              </el-input>
            </div>
            <!-- <div class="mr-[4px] flex items-center">
              <span class="mr-[4px]">燃油费比率</span>
              <el-input placeholder="请输入" v-model="item.fuel_rate">
                <template #append>%</template>
              </el-input>
            </div> -->
            <span
              class="hover:text-[#2080f0] cursor-pointer"
              @click.native="handleAdd"
            ><SvgIcon icon-class="Plus" class="text-[12px] inline"/></span>
            <span
              class="hover:text-[#2080f0] cursor-pointer ml-[4px]"
              @click="handleDelete(index)"
              v-if="cost.length > 1"
            ><SvgIcon icon-class="Minus" class="text-[12px] inline"/></span>
          </div>
        </template>

        <template v-if="billingType === 2">
          <div
            v-for="(item, index) in cost"
            :key="`${item.key}`"
            class="flex items-center whitespace-nowrap"
            :class="{ 'mt-[16px]': index !== 0 }"
          >
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">{{ `分段${index}：不超过` }}</span>
              <NumberRange
                separate="<重量≤"
                v-model="item.range"
                class="w-[260px]"
                suffix="g"
              />
            </div>
            <div class="mr-[4px] flex items-center">
              <span class="mr-[4px]">区间一口价</span>
              <el-input placeholder="请输入" v-model="item.one_price">
              </el-input>
            </div>
            <div class="mr-[4px] flex items-center">
              <span class="mr-[4px]">计费重量</span>
              <el-input placeholder="请输入" v-model="item.bill_weight">
                <template #append>g</template>
              </el-input>
            </div>
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">区间单价</span>
              <el-input placeholder="请输入" v-model="item.unit_price">
              </el-input>
            </div>
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">区间折扣</span>
              <el-input placeholder="请输入" v-model="item.discount">
              </el-input>
            </div>
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">区间附加费</span>
              <el-input placeholder="请输入" v-model="item.surcharge">
              </el-input>
            </div>
            <!-- <div class="mr-[4px] flex items-center">
              <span class="mr-[4px]">燃油费比率</span>
              <el-input placeholder="请输入" v-model="item.fuel_rate">
                <template #append>%</template>
              </el-input>
            </div> -->
            <span
              class="hover:text-[#2080f0] cursor-pointer"
              @click="handleAdd"
            ><SvgIcon icon-class="Plus" class="text-[12px] inline"/></span>
            <span
              class="hover:text-[#2080f0] cursor-pointer ml-[4px]"
              @click="handleDelete(index)"
              v-if="cost.length > 1"
            ><SvgIcon icon-class="Minus" class="text-[12px] inline"/></span>
          </div>
        </template>

        <template v-if="[3, 4].includes(billingType)">
          <div
            v-for="(item, index) in cost"
            :key="`${item.key}`"
            class="flex items-center whitespace-nowrap"
            :class="{ 'mt-[16px]': index !== 0 }"
          >
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">{{ `分段${index + 1}：` }}</span>
              <NumberRange
                :separate="billingType === 3 ? '<重量≤' : 'CBM<体积<='"
                v-model="item.range"
                class="w-[260px]"
                suffix="KG"
              />
            </div>
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">单价</span>
              <el-input placeholder="请输入" v-model="item.unit_price">
              </el-input>
            </div>
            <div class="mr-[16px] flex items-center">
              <span class="mr-[4px]">区间折扣</span>
              <el-input placeholder="请输入" v-model="item.discount">
              </el-input>
            </div>
            <span
              class="hover:text-[#2080f0] cursor-pointer"
              @click="handleAdd"
            ><SvgIcon icon-class="Plus" class="text-[12px] inline"/></span>
            <span
              class="hover:text-[#2080f0] cursor-pointer ml-[4px]"
              @click="handleDelete(index)"
              v-if="cost.length > 1"
            ><SvgIcon icon-class="Minus" class="text-[12px] inline"/></span>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ElMessage } from "element-plus";
import NumberRange from "@/components/NumberRange/index.vue";
import CurrencySelect from "@/components/CurrencySelect/index.vue";
const props = defineProps({
  data: { type: Object, default: () => ({}) },
  options: { type: Object, default: () => ({}) },
  billingType: { type: Number, default: "" },
  type:{type:String,default:""}
});
const emit = defineEmits(["changeCurrency"]);
const { costData = [] } = props.data || {};
const cost = ref([{ key: 1 }]);
const currency = ref();

const costLabel = computed(
  () =>
    ({
      1: "起重续价",
      2: "区间续价",
      3: "头程重量计费",
      4: "头程体积计费",
    }[props.billingType])
);
watch(
  () => [props.data, props.billingType],
  (val) => {
    const { costData = [], currency: _currency } = val?.[0] || {};
    if (!costData || !costData.length || !props.billingType) return;
    const updatedCost = costData.map((item, index) => {
      if (props.billingType == 1) {
        return {
          ...item,
          key: +new Date() + index,
        };
      } else {
        return {
          ...item,
          range: {
            min: item?.min_value || 0,
            max: item?.max_value || 0,
          },
          key: +new Date() + index,
        };
      }
    });
    cost.value = updatedCost;
    currency.value = _currency;
  }
);

const handleAdd = () => {
  cost.value.push({ key: +new Date() });
};

const handleDelete = (index) => {
  cost.value.splice(index, 1);
};

const handleWeight = (val, ind) => {
  if (cost.value?.length <= 1) {
    cost.value[ind].min_value = 0;
    return;
  }
  if (cost.value[ind].max_value > cost.value[ind - 1].max_value) {
    cost.value[ind].min_value = cost.value[ind - 1].max_value;
  } else {
    cost.value[ind].max_value = null
    ElMessage.warning(`重量要大于第${ind}的重量`);
  }
};

const submit = () => {
  return new Promise((resolve, reject) => {
    try {
      resolve({
        cost: JSON.parse(
          JSON.stringify(
            cost.value.map((n) => {
              if (props.billingType == 1) {
                return { ...n };
              } else {
                return {
                  ...n,
                  min_value: n?.range?.min || 0,
                  max_value: n?.range?.max || 0,
                  one_price: n?.one_price || 0,
                };
              }
            })
          )
        ),
        currency: currency.value,
      });
    } catch (e) {
      ElMessage.warning("请检查运输费用");
      console.error(e);
      reject("TransportCost");
    }
  });
};

const handleCurrency = (val) => {
  emit("changeCurrency", val);
};
const reset = () => {
  currency.value = "";
  cost.value = [{ key: 1 }];
};

defineExpose({ submit, reset });
</script>
<style lang="scss" scoped>
.transport-cost {
  :deep(.el-input-group__append) {
    padding: 0 10px;
  }
}
</style>
